<?php

include_once "quickcrud_connect.php";
include_once "quickcrud_common.php";
include "CF_mysql_com.php";
include_once "CF_all_com.php";

if (!isset($_REQUEST['crudset_id']) OR !isset($_REQUEST['project_id']) ){
	print 'Please select or create a project and set to use first';
	exit;
}

	$project_id = $_REQUEST['project_id'];
	$crudset_id = $_REQUEST['crudset_id'];


	$qry_project_info = "SELECT * FROM projects WHERE project_id = $project_id";

	$project_info = get_array_query($qry_project_info);
	
	$project_db = $project_info[1]['project_db'];
	$project_path = $project_info[1]['project_path'];
	$project_server = $project_info[1]['project_server'];
	$project_login = $project_info[1]['project_login'];
	$project_pass = $project_info[1]['project_pass'];
	$project_name = $project_info[1]['project_name'];
    $class_subpath = $project_info[1]['class_subpath'];
	$template_dir = $project_info[1]['template_dir'];	

    if(!empty($class_subpath)){
        $class_subpath = $class_subpath . '/';
        }


	
	$qry_set_info = "SELECT * FROM crudsets 
            JOIN tablesources ON tablesources.tablesource_id = crudsets.main_table 
    WHERE crudset_id = $crudset_id";

	$set_info = get_array_query($qry_set_info);

// fields from database
	$cs_name = $set_info[1]['cs_name'];
	$paging = $set_info[1]['paging'];
    $filter = $set_info[1]['filter'];
    $sort = $set_info[1]['sort'];
	$query = $set_info[1]['query'];
	$table_name = $set_info[1]['table_name'];
	$cs_type = $set_info[1]['cs_type'];
    $class_base_name = $set_info[1]['class_base_name'];
    $class_name = $set_info[1]['class_name'];
    $html_table_name = $set_info[1]['html_table_name'];
    $list_table_instance = $set_info[1]['list_table_instance'];
	$edit_base_class = $set_info[1]['edit_base_class'];
	$edit_class_name = $set_info[1]['edit_class_name'];
	$edit_instance = $set_info[1]['edit_instance'];
    $paging = $set_info[1]['paging'];
	$subdirectory = $set_info[1]['subdirectory'];
	$needs_login = $set_info[1]['needs_login'];
	
// calculated fields
    $process_page = $cs_name . '_proc.php';
    $list_page = $cs_name . '_list.php';
	$edit_page = $cs_name . '_edit.php';
    if($paging == 1){
        $no_paging = '';
        }
     else{
        $no_paging = '//';
        }
    if($sort == 1){
        $no_sort = '';
        $header_type = 'make_sort_heading';
        }
        $no_sort = '';
        $header_type = 'make_sort_heading';
     //else{
     //   $no_sort = '//';
     //   $header_type = 'make_simple_heading';
     //   }
    if($filter == 1){
        $no_filter = '';
        }
     else{
        $no_filter = '//';
        }
// Calcuate back directory $backdirectory from levels in subdirectory
	$subdirlevels = substr_count($subdirectory,'/');
	while ($subdirlevels > 0){
		$backdirectory .= "../";
		$subdirlevels --;
	}		
// comment out login logic or not
	if($needs_login == 1){
		$no_login = '';
	}
	else{
		$no_login = '//';
	}
// if subdirectory path not exists, create
if(!empty($subdirectory)){
	$subdirname = rtrim($subdirectory, "/");
		if(!file_exists('projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirname))
		{
			mkdir('projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirname);
		}
	}
	
// Active /inactivate



	$qry_get_keys = "SELECT variable_name FROM crudcols 
	JOIN variables ON variables.variable_id = crudcols.variable_id 
	WHERE crudset_id = $crudset_id AND crudcols.is_key = 1";
	
	$firstkey = true;
	$keys_info = get_array_query($qry_get_keys);
    if (is_array($keys_info)){
	foreach ($keys_info AS $key){
		if($firstkey){
			$getkeys .= "\$keys['" . $key['variable_name'] . "'] = addslashes(\$_REQUEST['" . $key['variable_name'] . "']);\n";
			$filterkeys .= "\$qry_list .= \" AND " . $key['variable_name'] . " = '\" . \$keys['" . $key['variable_name'] . "'] . \"' \";\n";
			$hiddenkeys .= "<input type='hidden' name='" . $key['variable_name'] . "' value='<?php print \$values['" . $key['variable_name'] . "'] ?>' />\n";
			//$str_key = $key['variable_name'];
			//$firstkey = false;
		}
		else{
			//$str_key .= "," . $key['variable_name'];
		}
	}
	}

	$str_row_limit = ". \" \$" . $list_table_instance . "->post_rowlimit\"";
	$str_qry_sort = " . \$" . $list_table_instance . "->make_query_sort()";
	$str_qry_filter = ". \$" . $list_table_instance . "->make_query_filter()";
	
	

	$str_query = "SELECT * FROM $table_name WHERE 1 ";
	
	// If passed a template file (tplfile), use it.  Else, use the default
	if(isset($_REQUEST['tplfile'])){
		$tplfile = $template_dir . $_REQUEST['tplfile'];
	}else{
		$tplfile = $template_dir . 'staticformTPL.php';
	}	
	$str_list_file = file_get_contents($tplfile);	
//	$str_list_file = file_get_contents($template_dir . 'staticformTPL.php');

    $str_list_file = str_replace("%class_subpath%",$class_subpath,$str_list_file);
    $str_list_file = str_replace("%subdirectory%",$subdirectory,$str_list_file);
    $str_list_file = str_replace("%backdirectory%",$backdirectory,$str_list_file);
    $str_list_file = str_replace("%no_login%",$no_login,$str_list_file);

	$str_list_file = str_replace("%str_row_limit%",$str_row_limit,$str_list_file);	
	$str_list_file = str_replace("%str_qry_filter%",$str_qry_filter,$str_list_file);	
	$str_list_file = str_replace("%str_qry_sort%",$str_qry_sort,$str_list_file);	
	$str_list_file = str_replace("%str_query%",$str_query,$str_list_file);	
	$str_list_file = str_replace("%process_page%",$process_page,$str_list_file);
	$str_list_file = str_replace("%edit_page%",$edit_page,$str_list_file);
	$str_list_file = str_replace("%class_name%",$class_name,$str_list_file);
	$str_list_file = str_replace("%class_base_name%",$class_base_name,$str_list_file);
	$str_list_file = str_replace("%html_table_name%",$html_table_name,$str_list_file);
	$str_list_file = str_replace("%cs_name%",$cs_name,$str_list_file);
	$str_list_file = str_replace("%header_type%",$header_type,$str_list_file);


	$str_list_file = str_replace("%connectinclude%",$project_name . "_connect.php",$str_list_file);
	$str_list_file = str_replace("%fieldinclude%",$cs_name . "_fields.php",$str_list_file);
	$str_list_file = str_replace("%cs_name%",$cs_name,$str_list_file);
	$str_list_file = str_replace("%str_key%",$str_key,$str_list_file);
	$str_list_file = str_replace("%no_paging%",$no_paging,$str_list_file);
	$str_list_file = str_replace("%no_sort%",$no_sort,$str_list_file);
	$str_list_file = str_replace("%no_filter%",$no_filter,$str_list_file);
            
	$str_list_file = str_replace("%edit_base_class%",$edit_base_class,$str_list_file);
	$str_list_file = str_replace("%edit_class_name%",$edit_class_name,$str_list_file);
    $str_list_file = str_replace("%edit_instance%",$edit_instance,$str_list_file);


// from db infor for querylist
	$qry_get_columns = "SELECT * FROM crudcols WHERE crudset_id = $crudset_id ORDER BY col_order ";
	$list_array = get_mysql_array($qry_get_columns);
	foreach ($list_array as $rowkey => $currentrow){
		$variable_id = $currentrow['variable_id'];
		$variable_name = lookup_value('variable_name', 'variables', "variable_id = $variable_id");
		
		if($currentrow['edit_type'] == 'querylist'){

			if(!empty($currentrow['list_query'])){
	
				$list_fields_str .= "\$array_" . $variable_name . "_list = get_array_query(\"" . $currentrow['list_query'] . "\");\n";
			}			
			if(!empty($currentrow['list_keycol'])){

			}
			if(!empty($currentrow['list_showcol'])){
				}			
		} // end list

        // lookup list
      if($currentrow['edit_type'] == 'commalist'){
          $list_string = $currentrow['list_query'];
          $commalist_array = explode(',',$list_string);
          $list_array_count = 1;
          foreach ($commalist_array as $list_element){
              $list_fields_str .= "\$array_" . $variable_name . "_list [$list_array_count] ['keyvalue'] = '$list_element';\n";
              $list_fields_str .= "\$array_" . $variable_name . "_list [$list_array_count] ['showvalue'] = '$list_element';\n";
              $list_array_count ++;
              } // end for each comma list
      }


} // end foreach listarray (colspec)


//--	
	
	
	//print "projects/" . $project_path . "/" . $subdirectory . $cs_name . "_fields.php";
	//exit;
	include_once "projects/" . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirectory . $cs_name . "_fields.php";
	
	foreach($fieldspec as $colname => $colspec){
		$form .="
<div id='entry_$colname' class='entries'>
\t<div class='heading'>$colname </div>
\t<div class='input'>";
		$formtype = $colspec['select'];
		if($formtype == 'T'){
			$form .= "\t\t<input type='text' name='$colname'  size='20' id='$colname' value='<?php print \$values['$colname'] ?>' />";
		}else if ($formtype == 'D'){
		
			$form .= "\t<?php 
			\$thevalue = \$values['$colname'];
			\$field = make_array_select(\$array_" . $colname . "_list, '$colname', 'keyvalue','showvalue',\$thevalue, 40, '', false);
			//print_r(\$array_" . $colname . "_list); 
			print \$field;
			?>\n";
		
		}else if ($formtype == 'A'){
		
			$cols = $colspec['size']; 
			$rows = $colspec['rows'];
		
			$form .= "\t\t<textarea name='$colname'  rows='$rows' cols='$cols' id='$colname'> <?php print \$values['$colname'] ?></textarea>";
			
		}else if ($formtype == 'C'){
		
			$cols = $colspec['size']; 
			$rows = $colspec['rows'];
			$form .= "<?php (\$values['$colname'] == '1')?\$checkcheck = \"CHECKED = 'true'\":\$checktext = \"CHECKED = 'false'\"?>\n";
			$form .= "\t\t<input type='hidden' name='$colname' value='0' />\n";
			$form .= "\t\t<input type='checkbox' name='$colname'  id='$colname' <?php print \$checkcheck ?> value='<?php print \$values['$colname'] ?>' />";
			
		}else if ($formtype == 'CAL'){
		
			$form .= "
				<input type='text' name='$colname' id='$colname' value='<?php print \$values['$colname'] ?>' style='display:none;' />
<img src='../jscalendar/img.gif' id='img_$colname' />
<span class='datespan' id='SD_$colname' ><?php print \$values['$colname'] ?></span>

<script type=\"text/javascript\">
Calendar.setup({
    ifFormat       :    \"%Y-%m-%d\",      // format of the input field
    daFormat       :    \"%B %d, %Y\",      // format of the input field
    align          :    \"T1\",           // alignment (defaults to Bl)
    showsTime      :    false,
    singleClick    :    true,
   // onClose       :    calldateonblur,
    inputField     :    \"$colname\",     // id of the input field
    displayArea     :    \"SD_$colname\",     // id of the Display field	
    button         :    \"img_$colname\"  // trigger for the calendar (button ID)
});
</script>

			
			
			";
		
		
		
		}else {
			$form .= "<?php print \$values['$colname'] ?>\n";
		}

		$form .="\t</div>
</div>
";
	}
	$form .= $hiddenkeys;
	
	
    $str_list_file = str_replace("%static_fields%",$form,$str_list_file);		
    $str_list_file = str_replace("%list_fields_str%",$list_fields_str,$str_list_file);		
    $str_list_file = str_replace("%getkeys%",$getkeys,$str_list_file);		
    $str_list_file = str_replace("%filterkeys%",$filterkeys,$str_list_file);		
    $str_list_file = str_replace("%hiddenkeys%",$hiddenkeys,$str_list_file);	
	
	
	
	
	
	
	
if($_REQUEST['output'] == 'screen')	{
    	echo "<html>\n<head>\n</head>\n<body>";
        echo "<TEXTAREA NAME=\"comments\" COLS='80' ROWS='20'>$str_list_file</TEXTAREA>\n";
        echo "</body></html>";


    }else{
		// if passed an outfile, write to it.  Else, use the default
		if(isset($_REQUEST['outfile'])){
			$outfile = 'projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirectory . $_REQUEST['outfile'];
		}else{
			$outfile = 'projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirectory . $cs_name . "_form.php";
		}
		file_put_contents($outfile,$str_list_file);	
	
        //file_put_contents('projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirectory . $cs_name . "_form.php",$str_list_file);
        $result = "Wrote List Page To $outfile";
        $result = urlencode($result);

        $header_text = "Location: leftmenu.php?project_id=$project_id&crudset_id=$crudset_id&result=$result";
        header($header_text); /* Redirect browser */
        exit;
	}

?>